package com.shujia.loaddata;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class LoadDataToMySql {
    public static void main(String[] args) throws Exception{
        Class.forName("com.mysql.jdbc.Driver");

        //创建两个读取数据的输入流
        BufferedReader br1 = new BufferedReader(new FileReader("stage2/data/consumer_behavior.csv"));
        BufferedReader br2 = new BufferedReader(new FileReader("stage2/data/merchant_info.csv"));

        //创建与mysql数据库的连接对象
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://master:3306/bigdata33?useUnicode=true&characterEncoding=utf-8&useSSL=false",
                "root",
                "123456");

        //创建数据库操作对象
        PreparedStatement p1 = conn.prepareStatement("insert into consumer_behavior values(?,?,?,?,?,?,?,?)");

        PreparedStatement p2 = conn.prepareStatement("insert into merchant_info values (?,?)");

        //先循环br1
        String line1 = null;
        while ((line1=br1.readLine())!=null){
            if(!line1.contains("user_id")){
                String[] info = line1.split(",");
                p1.setString(1,info[0]);
                p1.setString(2,info[1]);
                p1.setString(3,info[2]);
                p1.setString(4,info[3]);
                p1.setString(5,info[4]);
                p1.setString(6,info[5]);
                p1.setString(7,info[6]);
                p1.setString(8,info[7]);
                p1.executeUpdate();
            }
        }

        String line2 = null;
        while ((line2=br2.readLine())!=null){
            if(!line2.contains("merchant_id")){
                String[] info = line2.split(",");
                p2.setString(1,info[0]);
                p2.setString(2,info[1]);
                p2.executeUpdate();
            }
        }

        System.out.println("数据导入完毕！");


        br2.close();
        br1.close();

    }
}
